package com.example.leave.domain.approval.repo.impl;

import com.example.leave.domain.approval.aggregate.ApprovalRule;
import com.example.leave.domain.approval.infrastructure.mapper.ApprovalRuleMapper;
import com.example.leave.domain.approval.repo.ApprovalRuleRepo;
import com.example.leave.domain.approval.repo.dao.ApprovalDao;
import com.example.leave.domain.approval.repo.po.ApprovalRulePo;
import com.example.leave.domain.leave.aggregate.valueObject.LeaveType;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

/**
 * TODO
 *
 * @author lxh
 * @date 2020/11/27 上午10:05
 **/
@Service
public class ApprovalRuleRepoImpl implements ApprovalRuleRepo {
    private final ApprovalDao approvalDao;
    private final ApprovalRuleMapper mapper;

    public ApprovalRuleRepoImpl(ApprovalDao approvalDao, ApprovalRuleMapper mapper) {
        this.approvalDao = approvalDao;
        this.mapper = mapper;
    }

    @Override
    public ApprovalRule findOne(LeaveType leaveType, int duration) {
        List<ApprovalRulePo> list = approvalDao.findAll(
                (root, query, cb) -> {
                    List<Predicate> predicates = new ArrayList<>();
                    predicates.add(cb.equal(root.get("leaveType"), leaveType));
                    predicates.add(cb.greaterThanOrEqualTo(root.get("duration"), duration));
                    return cb.and(predicates.toArray(new Predicate[0]));
                },
                Sort.by(Sort.Direction.ASC, "duration"));
        return mapper.toApprovalRule(list.get(0));
    }
}
